﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Mrc.Config.Messages;
using Newtonsoft.Json;
using System.Linq;

namespace Mrc.Config
{
    public class NodeHealthCheckService : INodeHealthCheckService
    {
        private readonly IHttpClientFactory _httpClient;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private MrcConfigOptions _mrcConfigOptions;
        public NodeHealthCheckService(
            IHttpClientFactory httpClientFactory,
            IHttpContextAccessor httpContextAccessor,
            IOptions<MrcConfigOptions> options
            )
        {
            _httpClient = httpClientFactory;
            _httpContextAccessor = httpContextAccessor;
            _mrcConfigOptions = options.Value;
        }
        public Task Checked()
        {
            GC.GetTotalMemory(forceFullCollection: false);

            return Task.FromResult(true);
        }

        public async Task UpHealthInfo()
        {
            if (string.IsNullOrWhiteSpace(_mrcConfigOptions.MasterHost)) throw new ArgumentNullException("配置主节点不存在");
            var client = _httpClient.CreateClient();
            var info = GC.GetGCMemoryInfo();
            HealthMessages healthMessages = new HealthMessages
            {
                IP = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.FirstOrDefault(address => address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)?.ToString(),
                Port ="" ,//_httpContextAccessor.HttpContext.Connection.RemotePort.ToString(),
                HealthUrl = "",//_httpContextAccessor.HttpContext.Request.Host.ToString(),
                HostId = _mrcConfigOptions.HostId,
                TotalMemeoy = info.TotalAvailableMemoryBytes / 1024 / 1024,
                UseMoneoy = GC.GetTotalMemory(forceFullCollection: false) / 1024 / 1024
            };
            HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(healthMessages), Encoding.UTF8);
            await client.PostAsync($"{_mrcConfigOptions.MasterHost}/uploadNodeInfo", httpContent);
            throw new NotImplementedException();
        }
    }
}
